package ${rootPackageName};

import java.util.List;

import org.jow.common.db.DB;
import org.jow.core.Record;
import org.jow.core.support.Param;
import org.jow.worldsrv.core.event.OnHumanDataLoadBeginOne;
import org.jow.worldsrv.core.event.OnHumanDataLoadFinishOne;
import org.jow.worldsrv.support.observer.EventW;
import org.jow.worldsrv.character.human.HumanObject;

<#list methodsList as m>
<#list m.importPackages as package>
import ${package};
</#list>
</#list>
import org.jow.core.gen.JowGenFile;

@JowGenFile
public final class DataLoader {

	private static DataLoader instance = new DataLoader();
	
	private DataLoader() {}

	public static DataLoader inst() {
		return instance;
	}

	/**
	 * 加载玩家数据辅助方法
	 * @param humanObj 玩家对象
	 */
	public void load(HumanObject humanObj) {
	<#list methodsList as m>
		<#list m.fields as field>
		loadHumanData(humanObj, ${field.entity}.tableName, "${field.humanKey}");
		</#list>
	</#list>
	}
	
	/**
	 * 加载数据
	 * @param humanObj
	 * @param unitObj
	 * @param clazz
	 * @param tableName
	 * @param idParam
	 */
 	private void loadHumanData(HumanObject humanObj, String tableName, String idParam) { 		
		//准备环境
		DB prx = DB.newInstance(tableName);
		prx.findBy(false, idParam, humanObj.getId());
		prx.listenResult(this::_result_loadHumanData, "humanObj", humanObj, "tableName", tableName);
		
		//一次加载事件开始
		EventW.fire(new OnHumanDataLoadBeginOne(humanObj));
	}
	
	/**
	 * 数据库加载数据返回
	 * @param results
	 * @param context
	 */
	public void _result_loadHumanData(Param results, Param context) {
		// 玩家
		String tableName = context.get("tableName");
		HumanObject humanObj = context.get("humanObj");

		List<Record> records = results.get();
		switch (tableName) {
	<#list methodsList as m>
		<#list m.fields as field>
		case ${field.entity}.tableName:
			${field.name}(humanObj, records);
			break;
		</#list>
	</#list>
		default:
			break;
		}
		// 一次加载事件结束
		EventW.fire(new OnHumanDataLoadFinishOne(humanObj));
	}

	/**
	 * 根据表名获取关键字
	 * @param tableName
	 */
	public static String getKey(String tableName) {
		String key = null;
		switch (tableName) {
	<#list methodsList as m>
		<#list m.fields as field>
		case ${field.entity}.tableName:
			key = "${field.humanKey}";
			break;
		</#list>
	</#list>
		default:
			break;
		}
		return key;
	}
}
